import { Card, Divider, Form, Button, Input, message } from 'antd'
import styles from './index.module.less'
import { login } from '@/api/user'
import { useNavigate } from 'react-router-dom'
import { setUserInfo } from '@/store/reducers/user'
import { useDispatch } from 'react-redux'
import { getUserInfo } from '@/api/user'

export default function Login () {
  const navigate = useNavigate()
  const dispatch = useDispatch()

  const onFinish = async (values: any) => {
    // console.log('Success:', values)
    try {
      const res = await login(values)
      if (res.code === 200) {
        //保存到仓库
        dispatch(setUserInfo(res.data))

        const res1 = await getUserInfo()
        await dispatch(setUserInfo({ ...res1.data, token: res.data.token }))

        message.open({
          type: 'success',
          content: res.message,
          duration: 0.5,
          onClose () {
            navigate('/')
          }
        })
      } else {
        message.open({
          type: 'error',
          content: '用户名或密码有误！'
        })
      }
    } catch (error) {
      console.log(error)
    }
  }
  return (
    <div className={styles.root}>
      <Card className='card'>
        <h2 style={{ textAlign: 'center' }}>嗨购商城后台管理系统</h2>
        <Divider />
        <Form
          name='basic'
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          style={{ maxWidth: 600 }}
          initialValues={{ adminname: 'admin', password: '123456' }}
          onFinish={onFinish}
          autoComplete='off'
          size='large'
          labelAlign='left'
        >
          <Form.Item
            label='用户名：'
            name='adminname'
            rules={[
              { required: true, message: '用户名不能为空!' },
              {
                validator: (_, value) => {
                  const reg = /^[a-zA-Z0-9_-]{4,16}$/
                  return reg.test(value)
                    ? Promise.resolve()
                    : Promise.reject('用户名必须是5-16位！')
                }
              }
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label='密&nbsp;&nbsp;&nbsp;&nbsp;码：'
            name='password'
            rules={[
              { required: true, message: '密码不能为空!' },
              {
                validator: (_, value) => {
                  const reg = /^[a-zA-Z0-9]{6,16}$/
                  return reg.test(value)
                    ? Promise.resolve()
                    : Promise.reject('密码至少时6位！')
                }
              }
            ]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
            <Button type='primary' htmlType='submit' block>
              确认
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
